import datetime
from hashlib import md5
from dateutil import parser
import time
import datetime as dt
import cv2
import base64
import numpy as np
def globalCurrentTimeisOrNot(start_time,end_time):
   # 当前时间
    # print('---------------', start_time)
    # print('---------------', end_time)
    now_time = datetime.datetime.now()
    # 判断当前时间是否在范围时间内
    if start_time < now_time < end_time:
        return True
        
    return False

# 获取当天零点的时间
def getTodayZeroDate():
    now = datetime.datetime.now()
    zero_today = now - datetime.timedelta(hours = now.hour, minutes = now.minute, seconds = now.second, microseconds = now.microsecond)
    return zero_today

# 获取当天23点59分59秒的时间
def getTodayLastDate():
    now = datetime.datetime.now()
    zero_today = now - datetime.timedelta(hours = now.hour, minutes = now.minute, seconds = now.second, microseconds = now.microsecond)
    last_today = zero_today + datetime.timedelta(hours = 23, minutes = 59, seconds = 59)
    return last_today

# 获取指定小时分秒的iso时间
def getTodayAnyDate(hour, minute, second):
    now = datetime.datetime.now()
    zero_today = now - datetime.timedelta(hours = now.hour, minutes = now.minute, seconds = now.second, microseconds = now.microsecond)
    last_today = zero_today + datetime.timedelta(hours = hour, minutes = minute, seconds = second)
    return last_today

def globalStrMd5(data):
    bodymd5 = md5(data.encode('utf-8')).hexdigest()
    return bodymd5.upper()

def globalGetNowTime():
    now = parser.parse(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    return now

def globalTimeToString(time):
    # isodatetime格式时间转字符串
    if time is not None:
        return time.strftime("%Y-%m-%d %H:%M:%S")
    return ''

def globalTimeCompare(start, end):
    # 判断2个时间是不是都是当天
    date1 = dt.datetime.strptime(start, "%Y-%m-%d %H:%M:%S").date() 
    date2 = dt.datetime.strptime(end, "%Y-%m-%d %H:%M:%S").date() 
    Days = (date2 - date1).days 
    if Days == 0:
       # 代表小时
       return  'hour'
    return 'day'

def globalBase64ImageScale(imageSrc):
    # 按照固定宽度等比缩放base64格式图片
    imgData = base64.b64decode(imageSrc)
    nparr = np.frombuffer(imgData, np.uint8)
    img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    (x, y, chan) = img_np.shape
    x_s = 200
    y_s = int(y*x_s/x)
    img_new = cv2.resize(img_np, (x_s, y_s))
    image = cv2.imencode('.jpg', img_new)[1]
    base64_data = str(base64.b64encode(image))[2:-1]
    return base64_data


def is_valid_date(string):
    """
    判断字符串是否为一个有效的日期字符串
    """
    try:
        time.strptime(string, "%Y-%m-%d %H:%M:%S")
        return True
    except:
        return False
